package com.xjscrm.console.biz;

import com.xjscrm.common.entity.Captcha;
import com.xjscrm.common.exception.BusinessException;
import com.xjscrm.common.result.ResponseCode;
import com.xjscrm.common.utils.CaptchaUtils;
import com.xjscrm.console.param.captcha.CaptchaDto;
import com.xjscrm.console.vo.CaptchaVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.awt.image.BufferedImage;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
@Component
public class CaptchaService {

    /**
     * 拼图验证码允许偏差
     **/
    private static Integer ALLOW_DEVIATION = 3;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    public String checkImageCode(String imageKey, String imageCode) {
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        String text = ops.get("imageCode:" + imageKey);
        if(StringUtils.isBlank(text)){
            return "验证码已失效";
        }
        // 根据移动距离判断验证是否成功
        if (Math.abs(Integer.parseInt(text) - Integer.parseInt(imageCode)) > ALLOW_DEVIATION) {
            //验证失败，删除
            ops.getOperations().delete("imageCode:" + imageKey);
            return "验证失败，请控制拼图对齐缺口";
        }
        //验证成功，删除
        ops.getOperations().delete("imageCode:" + imageKey);
        return null;
    }


    public void saveImageCode(String key, String code) {
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        ops.set("imageCode:" + key, code, 10, TimeUnit.MINUTES);
    }


    public CaptchaVo getCaptcha(CaptchaDto captchaDto) {
        Captcha captcha = new Captcha();
        BeanUtils.copyProperties(captchaDto,captcha);
        //参数校验
        CaptchaUtils.checkCaptcha(captcha);
        //获取画布的宽高
        int canvasWidth = captcha.getCanvasWidth();
        int canvasHeight = captcha.getCanvasHeight();
        //获取阻塞块的宽高/半径
        int blockWidth = captcha.getBlockWidth();
        int blockHeight = captcha.getBlockHeight();
        int blockRadius = captcha.getBlockRadius();
        //获取资源图
        BufferedImage canvasImage = CaptchaUtils.getBufferedImage();
        //调整原图到指定大小
        canvasImage = CaptchaUtils.imageResize(canvasImage, canvasWidth, canvasHeight);
        //随机生成阻塞块坐标
        int blockX = CaptchaUtils.getNonceByRange(blockWidth, canvasWidth - blockWidth - 10);
        int blockY = CaptchaUtils.getNonceByRange(10, canvasHeight - blockHeight + 1);
        //阻塞块
        BufferedImage blockImage = new BufferedImage(blockWidth, blockHeight, BufferedImage.TYPE_4BYTE_ABGR);
        //新建的图像根据轮廓图颜色赋值，源图生成遮罩
        CaptchaUtils.cutByTemplate(canvasImage, blockImage, blockWidth, blockHeight, blockRadius, blockX, blockY);
        // 移动横坐标
        String nonceStr = UUID.randomUUID().toString().replaceAll("-", "");
        // 缓存
        saveImageCode(nonceStr,String.valueOf(blockX));
        //设置返回参数
        captcha.setNonceStr(nonceStr);
        captcha.setBlockY(blockY);
        captcha.setBlockSrc(CaptchaUtils.toBase64(blockImage, "png"));
        captcha.setCanvasSrc(CaptchaUtils.toBase64(canvasImage, "png"));

        CaptchaVo captchaVo = new CaptchaVo();
        BeanUtils.copyProperties(captcha,captchaVo);
        return captchaVo;
    }


    public void authByCaptcha(String nonceStr,String value){
        String msg = checkImageCode(nonceStr,value);
        if (StringUtils.isNotBlank(msg)) {
            throw new BusinessException(ResponseCode.CAPTCHA_UNALIGN,msg);
        }
    }
}
